import 'package:my_flutter_core/my_flutter_core.dart';

/// The service communicates with backend for [User] usage.
class UserService {
  final String _url = '/user';
  final HttpRequestService _httpRequestService = HttpRequestService();

  /// Retrieves the [User] from backend service with [id].
  Future<User> queryDetails(String id) async {
    // Gets the response of the http get request.
    final response = await _httpRequestService.get(
      '$_url/query-details',
      params: {'id': id},
    );

    // Parses the data from [Map<String, dynamic>] to [User].
    return User.fromJson(response.payload);
  }

  /// Retrieves users which are not in current account group from backend service.
  Future<List<User>> queryUsersNotInAccountGroup(
      int pageSize, int pageIndex, String keyword) async {
    // Gets the response of the http get request.
    final response = await _httpRequestService
        .get('$_url/query-users-not-in-account-group', params: {
      'pageSize': pageSize,
      'pageIndex': pageIndex,
      'keyword': keyword,
    });

    // Parses the data from [Map<String, dynamic>] to [User].
    return (response.payload as List<dynamic>)
        .map((p) => User.fromJson(p))
        .toList();
  }

  /// Retrieves current account group users from backend service.
  Future<List<User>> queryAccountGroupUsers(int pageSize, int pageIndex) async {
    // Gets the response of the http get request.
    final response = await _httpRequestService.get(
        '$_url/query-account-group-users',
        params: {'pageSize': pageSize, 'pageIndex': pageIndex});

    // Parses the data from [Map<String, dynamic>] to [User].
    return (response.payload as List<dynamic>)
        .map((p) => User.fromJson(p))
        .toList();
  }

  /// Updates the current logged-in user password.
  Future<bool> updateCurrentUserPassword(
      String currentPassword, String newPassword) async {
    final response = await _httpRequestService
        .post('$_url/update-current-user-password', body: {
      'currentPassword': currentPassword,
      'newPassword': newPassword,
    });

    return response.payload as bool;
  }

  /// Updates the current logged-in user info.
  Future<bool> updateCurrentUser(User user) async {
    final response = await _httpRequestService.post('$_url/update-current-user',
        body: user.toJson());

    return response.success;
  }

  /// Updates the user roles.
  Future<bool> updateRoles(User user) async {
    final response = await _httpRequestService.post('$_url/update-roles',
        body: user.toJson());

    return response.success;
  }
}
